<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">分类参数</a></el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                    title="注意：只允许为第三级分类设置相关参数！"
                    type="warning"
                    :closable="false"
                    effect="dark">
            </el-alert>
            <el-row class="selectCon">
                <el-col>
                    <span>选择商品分类：</span>
                    <!--级联选择器-->
                    <el-cascader
                            v-model="selectValues"
                            :options="categoriesOptions"
                            :props="cateProps"
                            @change="selectChange"></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" type="card" @tab-click="tabChangeClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button
                            :disabled="btnIsDisable"
                            type="primary"
                            size="mini"
                            @click="showAddParamsDialog"
                    >添加参数</el-button>
                    <el-table
                            border
                            :data="manyTableData"
                            style="width: 100%">
                        <el-table-column type="expand">
                            <!--展开行-->
                            <template v-slot="scope">
                                <el-tag
                                        :key="index"
                                        v-for="(item, index) in scope.row.attr_vals"
                                        closable
                                        :disable-transitions="false"
                                        @close="attrHandleClose(tag)">
                                    {{item}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="attrInputConfirm(scope.row)"
                                        @blur="attrInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                                type="index"
                                label="#">
                        </el-table-column>
                        <el-table-column
                                label="参数名称"
                                prop="attr_name">
                        </el-table-column>
                        <el-table-column
                                label="操作"
                                prop="id">
                            <template v-slot="scope">
                                <el-button type="primary"
                                           size="mini"
                                           @click="editParamsDialog(scope.row)"
                                           icon="el-icon-edit">修改</el-button>
                                <el-button type="danger"
                                           size="mini"
                                           icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button
                            :disabled="btnIsDisable"
                            type="primary"
                            @click="showAddParamsDialog"
                            size="mini">添加属性</el-button>
                    <el-table
                            border
                            :data="onlyTableData"
                            style="width: 100%">
                        <el-table-column type="expand">
                            <!--展开行-->
                        </el-table-column>
                        <el-table-column
                                type="index"
                                label="#">
                        </el-table-column>
                        <el-table-column
                                label="参数名称"
                                prop="attr_name">
                        </el-table-column>
                        <el-table-column
                                label="操作"
                                prop="id">
                            <template v-slot="scope">
                                <el-button type="primary"
                                           size="mini"
                                           @click="editParamsDialog(scope.row)"
                                           icon="el-icon-edit">修改</el-button>
                                <el-button type="danger"
                                           size="mini"
                                           icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--添加参数-->
        <el-dialog
                :title="(!addOrEditFlag?'添加':'修改') + titleText"
                :visible.sync="addParamsVisible"
                @close="addParamsOnClose"
                width="50%">
            <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsForm" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamsVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendAddParams">确 定</el-button>
            </span>
        </el-dialog>
        <!--<div id="vDom" class="class1">测试虚拟</div>-->
    </div>
</template>

<script>
    export default {

        props: [],

        components: {},

        data() {
            return {
                testVdom:"虚拟DOm",
                categoriesOptions: [],
                selectValues: [],
                cateProps: {
                    expandTrigger: "hover",
                    value: "cat_id",
                    label: "cat_name",
                    children: "children"
                },
                activeName: "many",
                manyTableData: [],
                onlyTableData: [],
                addParamsVisible: false,
                addParamsRules: {
                    attr_name: [
                        { required: true, message: '请输入参数名称', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ]
                },
                addParamsForm: {
                    attr_name: "",//参数名称	不能为空
                    attr_sel: "",//	[only,many]	不能为空
                    attr_vals: null,// 如果是 many 就需要填写值的选项，以逗号分隔
                    attr_id: null //参数Id
                },
                addOrEditFlag: false, //false 添加    true 修改
            };
        },

        watch: {},

        created() {
            this.getCategoriesData();
        },

        methods: {
            async getCategoriesData(){
                let {data:res} = await this.$http.get("categories");
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.categoriesOptions = res.data;
            },
            //级联选择器回调函数
            selectChange(){
                console.log(this.selectValues);
                this.getCategoriesAttrData();
            },
            //切换选项卡回调函数
            tabChangeClick(){
                console.log(this.activeName);
                this.getCategoriesAttrData();
            },
            async getCategoriesAttrData(){
                if(this.selectValues.length !== 3){
                    this.manyTableData = [];
                    this.onlyTableData = [];
                    this.selectValues = [];
                    return this.$message.error("只允许为三级分类设置参数！");
                }
                let {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
                    params: {sel:this.activeName}
                });
                res.data.forEach((item, index)=>{
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
                    item.inputVisible = false;
                    item.inputValue = "";
                });
                console.log("--------------",res);
                if(this.activeName === "many"){
                    this.manyTableData = res.data;
                }else {
                    this.onlyTableData = res.data;
                }
            },
            //展示添加属性对话框
            showAddParamsDialog(){
                this.addOrEditFlag = false;
                this.addParamsVisible = true;
            },
            //对话框中点击确定按钮发送新建或者修改后的参数数据
            sendAddParams(){
                this.$refs.addParamsForm.validate(async (valid) => {
                    if(!valid) return;
                    this.addParamsForm.attr_sel = this.activeName;

                    if(this.addOrEditFlag){//修改
                        var {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.addParamsForm.attr_id}`,this.addParamsForm);
                        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
                    }else {//添加
                        var {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,this.addParamsForm);
                        if(res.meta.status !== 201) return this.$message.error(res.meta.msg);
                    }
                    await this.getCategoriesAttrData();
                    this.$message.success(res.meta.msg);
                    this.addParamsVisible = false;
                });
            },
            addParamsOnClose(){
                this.addParamsForm.attr_name = "";
                this.$refs.addParamsForm.resetFields();
            },
            //修改参数
            editParamsDialog(row){
                console.log("修改参数源数据", row);
                this.addOrEditFlag = true;
                this.addParamsForm.attr_name = row.attr_name;
                this.addParamsForm.attr_id = row.attr_id;
                /*addParamsForm: {
                    attr_name: "",//参数名称	不能为空
                        attr_sel: "",//	[only,many]	不能为空
                        attr_vals: null// 如果是 many 就需要填写值的选项，以逗号分隔
                }*/
                this.addParamsVisible = true;
            },
            //tag标签关闭事件回调
            attrHandleClose(data){

            },
            //展示参数输入框
            showInput(data){
                data.inputVisible = true;
                this.$nextTick(()=>{
//                    console.log(this.$refs,this.$refs.saveTagInput);
                    this.$refs.saveTagInput.focus();
                });
            },
            //回车键抬起或者鼠标失去焦点回调
            async attrInputConfirm(data){
                console.log("attrInputConfirm===>",data);
                data.inputVisible = false;
                if(!data.inputValue){
                    return
                }else {
                    if(data.attr_vals.includes(data.inputValue)){
                        return this.$message.error("该属性已存在");
                    }
                    data.attr_vals.push(data.inputValue);
                    let sendData = {
                        attr_name: data.attr_name,
                        attr_sel: data.attr_sel,
                        attr_vals: data.attr_vals.join(",")
                    };
                    let {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${data.attr_id}`, sendData);
                    if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
                    this.$message.success(res.meta.msg);
                }
                data.inputValue = "";
            },
            /*cheangeTestVdom(){
                //虚拟DOM 性能  减少浏览器的重绘和回流
                /!*this.testVdom = "测试虚拟DOM01";
                this.testVdom = "测试虚拟DOM02";
                this.testVdom = "测试虚拟DOM03";
                this.testVdom = "测试虚拟DOM04";
                this.testVdom = "测试虚拟DOM05";
                this.testVdom = "测试虚拟DOM06";*!/


                /!*let a = {
                    data: "testVdom",
                    vDom: "div",
                    id: 123,
                    text: "测试虚拟",
                    attr: {
                        id1:"vDom",
                        class1: "vDom",
                    }
                }*!/


                /!*DOM耗费性能的地方 重绘和回流
                let vDom = document.getElementById("vDom");
                vDom.innerHTML = "测试虚拟DOM01"; 重绘
                vDom.innerHTML = "测试虚拟DOM02"; 重绘
                vDom.innerHTML = "测试虚拟DOM03"; 重绘
                vDom.innerHTML = "测试虚拟DOM04";*!/
            }*/
        },

        computed: {
            cateId(){
                return this.selectValues[this.selectValues.length-1]
            },
            btnIsDisable(){
                return this.selectValues.length !== 3
            },
            titleText(){
                return this.activeName === "many"?"动态参数":"静态属性"
            }
        }
    };
</script>

<style lang="scss" type="text/scss" scoped>
    .selectCon{
        margin-top: 10px;
    }
    .el-tabs{
        margin-top: 20px;
    }
    .el-tag{
        margin: 5px;
        user-select: none;
    }
    .input-new-tag{
        margin: 0 5px;
        width: 150px;
    }
    .button-new-tag{
        margin-left: 5px;
    }
</style>
